/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentanaInfo.java
 *
 * Created on 19-nov-2010, 11:47:25
 */
package Presentacion;

import Dominio.Arco;
import Dominio.Nodo;
import Dominio.Vertice;
import Negocio.Busqueda;
import Negocio.TempleSimulado;
import Persistencia.DAOCallejero;
import Persistencia.DAOCoordenadas;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author beatriz
 */
public class VentanaInfo extends javax.swing.JFrame {

    DAOCallejero daoCallejero = null;
    DAOCoordenadas daoCoordenadas = null;
    Busqueda busqueda = null;
    int tipoBusqueda;
    int[] maximos = new int[3];
    int nodoOrigen;
    int nodoDestino;
    Nodo nodoSolucion;
    int cota;

    /** Creates new form VentanaInfo */
    public VentanaInfo() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PanelSalida = new javax.swing.JScrollPane();
        AreaInfo = new javax.swing.JTextPane();
        Comenzar_btn = new javax.swing.JButton();
        CuadroOrigen = new javax.swing.JTextField();
        origen = new javax.swing.JLabel();
        destino = new javax.swing.JLabel();
        CuadroDestino = new javax.swing.JTextField();
        ComboBoxBusquedas = new javax.swing.JComboBox();
        algoritmoBusqueda_lbl = new javax.swing.JLabel();
        leerFichero_btn = new javax.swing.JButton();
        cota_label = new javax.swing.JLabel();
        cota_texto = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        ArchivoMenu = new javax.swing.JMenu();
        cargarNuevoCSV_ArchivoItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Practica I - Inteligencia Artificial");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        PanelSalida.setViewportView(AreaInfo);

        Comenzar_btn.setText("Comenzar");
        Comenzar_btn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Comenzar_btnMouseClicked(evt);
            }
        });
        Comenzar_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Comenzar_btnActionPerformed(evt);
            }
        });

        CuadroOrigen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CuadroOrigenActionPerformed(evt);
            }
        });

        origen.setText("Origen:");

        destino.setText("Destino:");

        CuadroDestino.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CuadroDestinoActionPerformed(evt);
            }
        });

        ComboBoxBusquedas.setBackground(new java.awt.Color(255, 255, 255));
        ComboBoxBusquedas.setFont(new java.awt.Font("Dialog", 2, 12)); // NOI18N
        ComboBoxBusquedas.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- Seleccione la búsqueda -", "Anchura", "Profundidad", "Profundidad Acotada", "Profundidad Iterativa", "Coste Uniforme", "A*", "Temple Simulado", " " }));
        ComboBoxBusquedas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ComboBoxBusquedasMouseClicked(evt);
            }
        });
        ComboBoxBusquedas.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ComboBoxBusquedasItemStateChanged(evt);
            }
        });

        algoritmoBusqueda_lbl.setText("Algoritmo de búsqueda:");

        leerFichero_btn.setText("Leer Fichero");
        leerFichero_btn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                leerFichero_btnMouseClicked(evt);
            }
        });
        leerFichero_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                leerFichero_btnActionPerformed(evt);
            }
        });

        cota_label.setText("Cota:");

        cota_texto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cota_textoActionPerformed(evt);
            }
        });

        ArchivoMenu.setText("Archivo");
        ArchivoMenu.setAutoscrolls(true);

        cargarNuevoCSV_ArchivoItem.setText("Cargar nuevo CSV...");
        ArchivoMenu.add(cargarNuevoCSV_ArchivoItem);

        jMenuBar1.add(ArchivoMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(139, 139, 139)
                        .addComponent(leerFichero_btn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 400, Short.MAX_VALUE)
                        .addComponent(Comenzar_btn))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(PanelSalida, javax.swing.GroupLayout.DEFAULT_SIZE, 754, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(origen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(477, 477, 477))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(destino, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
                                .addGap(172, 172, 172))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(CuadroDestino, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(CuadroOrigen, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cota_label)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cota_texto, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(algoritmoBusqueda_lbl)
                            .addComponent(ComboBoxBusquedas, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(origen)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(CuadroOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(destino)
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(CuadroDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cota_label)
                            .addComponent(cota_texto, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(23, 23, 23))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(algoritmoBusqueda_lbl)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ComboBoxBusquedas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addComponent(PanelSalida, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Comenzar_btn)
                    .addComponent(leerFichero_btn))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void Comenzar_btnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Comenzar_btnMouseClicked

        nodoOrigen = Integer.parseInt(CuadroOrigen.getText());
        nodoDestino = Integer.parseInt(CuadroDestino.getText());
        tipoBusqueda = ComboBoxBusquedas.getSelectedIndex();
        maximos[0] = 462;
        maximos[1] = 9;
        maximos[2] = 25;
        cota = 1000000;
        Nodo sol = null;
        if (tipoBusqueda == 3) {
            cota = Integer.parseInt(cota_texto.getText());
        }
        if (tipoBusqueda == 4) {
            cota = 1;
        }
        if (tipoBusqueda != 7) {
            busqueda = new Busqueda(nodoOrigen, nodoDestino, tipoBusqueda, maximos[0], maximos[1], maximos[2]);
            nodoSolucion = busqueda.lanzarBusqueda(cota);
        } else {
            TempleSimulado busquedaTemple = new TempleSimulado(nodoOrigen, nodoDestino, maximos[0], maximos[1], maximos[2], cota);
            busqueda = new Busqueda(nodoOrigen, nodoDestino, 1, maximos[0], maximos[1], maximos[2]);
            sol = busqueda.lanzarBusqueda(cota);

            if (sol == null) {
                AreaInfo.setText("no hay solucion inicial");
            } else {
                AreaInfo.setText("Looking for...");
                AreaInfo.setText(imprimeSolucion(sol));
                nodoSolucion = busquedaTemple.lanzarTempleSimulado(sol);
            }
        }

        if (nodoSolucion == null) {
            AreaInfo.setText("No hay solucion");
        } else {
            AreaInfo.setText(imprimeSolucion(nodoSolucion));
        }
        System.out.println("\nFIN");

//        leerFicheroArcos();
//                PruebaMemoria.llenarMemoria();
//        AreaInfo.setText(info);
    }//GEN-LAST:event_Comenzar_btnMouseClicked

    private void CuadroDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CuadroDestinoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CuadroDestinoActionPerformed

    private void CuadroOrigenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CuadroOrigenActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CuadroOrigenActionPerformed

    private void Comenzar_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Comenzar_btnActionPerformed
    }//GEN-LAST:event_Comenzar_btnActionPerformed

    private void leerFichero_btnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_leerFichero_btnMouseClicked
        leerFicheroVertices();
    }//GEN-LAST:event_leerFichero_btnMouseClicked

    private void leerFichero_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_leerFichero_btnActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_leerFichero_btnActionPerformed

    private void cota_textoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cota_textoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cota_textoActionPerformed

    private void ComboBoxBusquedasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ComboBoxBusquedasMouseClicked
    }//GEN-LAST:event_ComboBoxBusquedasMouseClicked

    private void ComboBoxBusquedasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_ComboBoxBusquedasItemStateChanged
       
        AreaInfo.setText(" ");
        if (ComboBoxBusquedas.getSelectedIndex() == 3) {
            cota_texto.setVisible(true);
            cota_label.setVisible(true);
        } else {
            cota_texto.setVisible(false);
            cota_label.setVisible(false);
        }
    }//GEN-LAST:event_ComboBoxBusquedasItemStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new VentanaInfo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu ArchivoMenu;
    private javax.swing.JTextPane AreaInfo;
    private javax.swing.JComboBox ComboBoxBusquedas;
    private javax.swing.JButton Comenzar_btn;
    private javax.swing.JTextField CuadroDestino;
    private javax.swing.JTextField CuadroOrigen;
    private javax.swing.JScrollPane PanelSalida;
    private javax.swing.JLabel algoritmoBusqueda_lbl;
    private javax.swing.JMenuItem cargarNuevoCSV_ArchivoItem;
    private javax.swing.JLabel cota_label;
    private javax.swing.JTextField cota_texto;
    private javax.swing.JLabel destino;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JButton leerFichero_btn;
    private javax.swing.JLabel origen;
    // End of variables declaration//GEN-END:variables

    private void leerFicheroArcos() {
        StringBuffer texto = new StringBuffer();
        String line = "";
        String[] datos;
        Arco arco;
        Integer orign, destiny, distancia, bares, ocio;
        String calle;

        if (daoCallejero == null) {
            try {
                daoCallejero = new DAOCallejero();
            } catch (SQLException ex) {
                Logger.getLogger(VentanaInfo.class.getName()).log(Level.SEVERE, null, ex);
                System.out.print("Error al conectar con la base de datos");
            }
        }

        try {
            File archivo = new File("/home/beatriz/NetBeansProjects/GrafoInteligenciaP1/misc/arcos.txt");
            FileReader fr = new FileReader(archivo);
            BufferedReader bf = new BufferedReader(fr);
            while ((line = bf.readLine()) != null) {
                datos = line.split(",");
                System.out.println(line);
                if (datos.length == 6) {
                    orign = Integer.parseInt(datos[0]);
                    destiny = Integer.parseInt(datos[1]);
                    distancia = Integer.parseInt(datos[2]);
                    bares = Integer.parseInt(datos[3]);
                    ocio = Integer.parseInt(datos[4]);
                    calle = datos[5];
                    arco = new Arco(orign, destiny, distancia, bares, ocio, calle);
                    daoCallejero.insert(arco);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void leerFicheroVertices() {
        StringBuffer texto = new StringBuffer();
        String line = "";
        String[] datos;
        Vertice vertice;
        Integer idNodo;
        Float latitud, longitud;

        if (daoCoordenadas == null) {
            try {
                daoCoordenadas = new DAOCoordenadas();
            } catch (SQLException ex) {
                Logger.getLogger(VentanaInfo.class.getName()).log(Level.SEVERE, null, ex);
                System.out.print("Error al conectar con la base de datos");
            }
        }

        try {
            File archivo = new File("/home/beatriz/NetBeansProjects/GrafoInteligenciaP1/misc/vertices.txt");
            FileReader fr = new FileReader(archivo);
            BufferedReader bf = new BufferedReader(fr);
            while ((line = bf.readLine()) != null) {
                datos = line.split(",");
                System.out.println(line);
                if (datos.length == 3) {
                    idNodo = Integer.parseInt(datos[0]);
                    latitud = Float.parseFloat(datos[1]);
                    longitud = Float.parseFloat(datos[2]);
                    vertice = new Vertice(idNodo, latitud, longitud);
                    daoCoordenadas.insert(vertice);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String imprimeSolucion(Nodo s) {
        Nodo aux = s;
        float costeTotal = 0;
        LinkedList<Integer> list = new LinkedList<Integer>();
        while (aux.getNodoPadre() != null) {
            list.addFirst(aux.getEstado().getIdNodo());
            costeTotal += aux.getEstado().getCosto();
            aux = aux.getNodoPadre();
        }
        costeTotal += aux.getEstado().getCosto();
        list.addFirst(aux.getEstado().getIdNodo());
        return list.toString() + "\nCoste: " + s.getCoste() + "\nProfundidad: " + s.getEstado().getProfundidad();

    }
//    private int[] buscarMaximos() {
//        LinkedList<Arco> arcos = new LinkedList<Arco>();
//        int[] max = new int[3];
//        if (dao == null) {
//            try {
//                dao = new DAOCallejero();
//            } catch (SQLException ex) {
//                Logger.getLogger(VentanaInfo.class.getName()).log(Level.SEVERE, null, ex);
//                System.out.print("Error al conectar con la base de datos");
//            }
//        }
//        arcos = dao.select("max(distancia)", "");
//        max[0] = arcos.getFirst().getDistancia().intValue();
//        System.out.println("NNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
//        arcos.removeFirst();
//        arcos = dao.select("max(bares)", "");
//        max[1] = arcos.getFirst().getBares().intValue();
//        arcos.removeFirst();
//        arcos = dao.select("max(ocio)", "");
//        max[2] = arcos.getFirst().getOcio().intValue();
//
//        return max;
//
//    }
}
